package com.lincoln.redis.server.controller;

import com.lincoln.bean.ApiCode;
import com.lincoln.bean.ApiCodeException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

/**
 * redis操作
 *
 * @author lincoln
 */
@CrossOrigin
@RestController
@RequestMapping("/redis")
public class RedisController {
    Jedis jedis;

    @PreAuthorize("hasAnyAuthority('admin','redis-server')")
    @PostMapping("/set")
    public ApiCode set(String key, String value) {
        return ApiCode.build(jedis.set(key, value));
    }

    @PreAuthorize("hasAnyAuthority('admin','redis-server')")
    @GetMapping("/get")
    public ApiCode get(String key) {
        return ApiCode.build(jedis.get(key));
    }

    @PreAuthorize("hasAnyAuthority('admin','redis-server')")
    @PostMapping("/push")
    public ApiCode push(Boolean right, String key, String[] values) throws ApiCodeException {
        if (right == null) {
            throw new ApiCodeException(10001);
        }
        if (right) {
            return ApiCode.build(jedis.rpush(key, values));
        } else {
            return ApiCode.build(jedis.lpush(key, values));
        }
    }

    @PreAuthorize("hasAnyAuthority('admin','redis-server')")
    @PostMapping("/pop")
    public ApiCode pop(Boolean right, String key) throws ApiCodeException {
        if (right == null) {
            throw new ApiCodeException(10001);
        }
        if (right) {
            return ApiCode.build(jedis.rpop(key));
        } else {
            return ApiCode.build(jedis.lpop(key));
        }
    }

    @PreAuthorize("hasAnyAuthority('admin','redis-server')")
    @GetMapping("/keys")
    public ApiCode keys(String keys) {
        return ApiCode.build(jedis.keys(keys));
    }

}
